package ldkxingzhe.ldkxingzhedemo.others;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import ldkxingzhe.ldkxingzhedemo.R;
import ldkxingzhe.ldkxingzhedemo.utils.LogDemo;


/**
 * Created by xingzhe on 15/10/10.
 */
public class DownLoadActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = DownLoadActivity.class.getSimpleName();
    private long id = -2;
    Resources resources;
    private DownloadReceiver receiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buttons);
        ((TextView)findViewById(R.id.title)).setText("测试DownloaderManager");
        Button button = (Button)findViewById(R.id.button1);
        button.setText("点击开始下载");
        button.setOnClickListener(this);
        resources = getResources();
        receiver = new DownloadReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.intent.action.DOWNLOAD_COMPLETE");
        filter.setPriority(999);
        registerReceiver(receiver, filter);
    }

    @Override
    public void onClick(View v) {
        String url = "http://www.apk3.com/uploads/soft/201504/yjzcs.035636.apk";
        LogDemo.v(TAG,"Button1 was clicked, url is " + url);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
        request.setTitle("ldkxingzhedemo");
        request.setDescription("请勿退出");

        // in order for this to run , you must use the android 2.3 or later to compile your app
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
            request.allowScanningByMediaScanner();
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        }
        request.setDestinationInExternalPublicDir(getExternalCacheDir().getAbsolutePath(),"SCO.apk");

        // get downloaded service and enqueue file
        DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        // 返回下载的id, 这个用于等下检测完成时间是否完成.
        id = downloadManager.enqueue(request);
        LogDemo.v(TAG,"start download, and id is " + id);
    }

    @Override
    protected void onDestroy() {
        if(receiver != null){
            unregisterReceiver(receiver);
        }
        super.onDestroy();
    }

    class DownloadReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if(id != intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1)){
                LogDemo.v(TAG,"Download complete, but not my task");
                return;
            }

            LogDemo.v(TAG,"Download complete, and is my task");

            DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
            Intent install = new Intent(Intent.ACTION_VIEW);

            Uri uri = downloadManager.getUriForDownloadedFile(id);
            install.setDataAndType(uri,"application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            LogDemo.d(TAG, "start installing application");
            context.startActivity(install);
        }
    }
}
